package com.xyz.service;

import com.free.common.vo.ResultModel;
import com.free.utils.crypt.DESCrypt;
import com.xyz.dao.logic.CustomerLogic;
import com.xyz.domain.constants.EhCacheConstants;
import com.xyz.domain.constants.SysConstants;
import com.xyz.domain.model.RestPwdModel;
import com.xyz.domain.table.CCustomer;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class RestPwdService extends BaseService {

    @Autowired
    CustomerLogic customerLogic;

    public ResultModel restPwd(RestPwdModel restPwdModel){
        ResultModel checkRes = restPwdCheck(restPwdModel);
        if(!checkRes.isSuccess()){
            return checkRes;
        }
        return udpCustomerPwd(restPwdModel);
    }

    public ResultModel udpCustomerPwd(RestPwdModel restPwdModel){
        CCustomer customerInfo = customerLogic.selectByMobile(restPwdModel.getPhone());
        String randomNums = randomNumbers(8);
        String encryptPwd = DESCrypt.encrypt(randomNums, SysConstants.PASSWORD_ENCRYPT_KEY);
        customerInfo.setPassword(encryptPwd);
        Integer res = customerLogic.udpCustmerPassword(customerInfo);
        if(res > 0){
            return ResultModel.success(randomNums);
        }
        return ResultModel.failure();
    }

    public ResultModel isPhoneValid(RestPwdModel restPwdModel){
        if(StringUtils.isEmpty(restPwdModel.getPhone())) {
            return ResultModel.failure(null, "请输入手机号码");
        }
        if(StringUtils.isEmpty(restPwdModel.getToken())) {
            return ResultModel.failure(null, "请输入验证码");
        }
        if(StringUtils.isEmpty(restPwdModel.getToken())){
            return ResultModel.failure(null, "请求不正确");
        }
        String validateNo = getStringFromQueue(EhCacheConstants.TokenKaptchaCache, restPwdModel.getToken());
        if(!StringUtils.endsWithIgnoreCase(validateNo,restPwdModel.getValidateNo())){
            return ResultModel.failure(null, "请输入正确的验证码");
        }
        CCustomer customerInfo = customerLogic.selectByMobile(restPwdModel.getPhone());
        if(customerInfo == null){
            return ResultModel.failure(null, "请输入正确的手机号");
        }
        return ResultModel.success();
    }

    private ResultModel restPwdCheck(RestPwdModel restPwdModel){
        if(StringUtils.isEmpty(restPwdModel.getSmsCode())){
            return ResultModel.failure(null, "请输入手机验证码");
        }
        String phoneNum = getStringFromQueue(EhCacheConstants.SmsPhoneNumCache, restPwdModel.getPhone());
        if(!StringUtils.equalsIgnoreCase(restPwdModel.getSmsCode(), phoneNum)){
            return ResultModel.failure(null, "请输入正确的手机验证码");
        }
        return ResultModel.success();
    }

}
